﻿using Azure.Core;
using Common.Exceptions;
using Common.Models;
using Common.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Wallpaper.Models.DTOs.Requests.Role;
using Wallpaper.Models.DTOs.Responses.Role;
using Wallpaper.Models.Entities;
using Wallpaper.Models.Options;
using Wallpaper.Services.IService;
using Wallpaper.Services.Service;
using WallpaperApi.Filter;

namespace WallpaperApi.Controllers
{
    [Route("api/roles")]
    [ApiController]
    [Authorize]
    public class RoleController : BaseController
    {
        readonly IRoleService _roleService;
        readonly ILogger<RoleController> _logger;

        public RoleController(IRoleService roleService, ILogger<RoleController> logger)
        {
            _roleService = roleService;
            _logger = logger;
        }


        /// <summary>
        /// 新增角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize("system:roles:add")]
        public async Task<ApiResponse<object>> Create([FromBody] CreateRoleRequest request)
        {
             await _roleService.CreateAsync(request);
             _logger.LogInformation("角色创建成功 - 操作者:{Account}, 角色名称:{RoleName}, 角色编码:{RoleCode}, 状态:{IsEnabled}",
                     Account, request.RoleName, request.RoleCode, request.IsEnabled ? "启用" : "禁用");
             return ApiResponse<object>.Success();
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        /// <param name="id"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        [Authorize("system:roles:edit")]
        public async Task<ApiResponse<Object>> Update(string id, [FromBody] CreateRoleRequest request)
        {
            await _roleService.UpdateAsync(id, request);
            _logger.LogInformation("角色更新成功 - 操作者:{Account}, 角色ID:{RoleId}, 角色名称:{RoleName}, 角色编码:{RoleCode}, 状态:{IsEnabled}",
            Account, id, request.RoleName, request.RoleCode, request.IsEnabled ? "启用" : "禁用");
            return ApiResponse<Object>.Success();
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpDelete("{id}")]
        [Authorize("system:roles:delete")]
        public async Task<ApiResponse<Object>> Delete(string id)
        {
            bool result = await _roleService.DeleteAsync(id);
            _logger.LogInformation($"角色删除成功 - 操作者:{Account}删除角色ID：{id}的角色信息");
            return ApiResponse<Object>.Success();
        }


        /// <summary>
        /// 获取所有角色选项列表
        /// 用于前端下拉选择框等场景
        /// </summary>
        /// <returns>包含角色选项列表的API响应</returns>
        [HttpGet("role-options")]
        public async Task<ApiResponse<List<RoleOptionResponse>>> GetRoleOptions()
        {
            var result = await _roleService.GetRoleOptionsAsync();
            return ApiResponse<List<RoleOptionResponse>>.Success(result);
        }

        /// <summary>
        /// 根据角色ID获取已绑定的管理员信息
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns>包含绑定管理员选项列表的API响应</returns>
        [HttpGet("{roleId}/bind-info")]
        public async Task<ApiResponse<List<OptionsResponse>>> GetBindInfo(string roleId)
        {
            var result = await _roleService.GetBindInfoAsync(roleId);
            return ApiResponse<List<OptionsResponse>>.Success(result);
        }

        /// <summary>
        /// 绑定角色与管理员关系
        /// 将指定的管理员绑定到角色，同时解绑该角色下的其他管理员
        /// </summary>
        /// <param name="request">绑定角色请求参数</param>
        /// <returns>操作是否成功的API响应</returns>
        /// <exception cref="ArgumentException">当请求参数为空时抛出</exception>
        /// <exception cref="BusinessException">当角色不存在或业务规则违反时抛出</exception>
        [HttpPost("bind-role")]
        public async Task<ApiResponse<bool>> BindRoleAsync([FromBody] BindRoleRequest request)
        {
            // 不需要手动验证ModelState
            var result = await _roleService.BindRoleAsync(request.RoleId, request.AdminIds);
            return ApiResponse<bool>.Success(result);
        }

        /// <summary>
        /// 角色分页
        /// </summary>
        /// <param name="queryRequest"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize("system:roles:query")]
        public async Task<ApiResponse<PagedResult<RolePageResponse>>> Page([FromQuery] RoleQueryRequest queryRequest)
        {
            PagedResult<RolePageResponse> pagedResult = await _roleService.PageAsync(queryRequest);
            return ApiResponse<PagedResult<RolePageResponse>>.Success(pagedResult);
        }


        /// <summary>
        /// 获取角色已绑定的菜单
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpGet("{roleId}/menus")]
        public async Task<ApiResponse<List<OptionsResponse>>> GetRoleMenus(string roleId)
        {
            List<OptionsResponse> options = await _roleService.GetRoleBindMenuAsync(roleId);
            return ApiResponse<List<OptionsResponse>>.Success(options);
        }

        /// <summary>
        /// 角色绑定菜单
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="menuIds"></param>
        /// <returns></returns>
        [HttpPut("{id}/bind-menus")]
        public async Task<ApiResponse<Object>> BindMenu(string id, [FromBody] List<string> menuIds)
        {
           bool result= await _roleService.BindMenuAsync(id, menuIds);
           return ApiResponse<Object>.Success();
        }





        /// <summary>
        /// 获取角色已绑定的权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpGet("{roleId}/permissions")]
        public async Task<ApiResponse<List<string>>> GetRolePermissions(string roleId)
        {
            List<string> options = await _roleService.GetRolePermissionsAsync(roleId);
            return ApiResponse<List<string>>.Success(options);
        }


        /// <summary>
        /// 角色绑定权限
        /// </summary>
        /// <param name="id"></param>
        /// <param name="permissionIds"></param>
        /// <returns></returns>
        [HttpPut("{id}/bind-permissions")]
        public async Task<ApiResponse<Object>> BindPermission(string id, [FromBody] List<string> permissionIds)
        {
            bool result = await _roleService.BindPermissionAsync(id, permissionIds);
            return ApiResponse<Object>.Success();
        }


    }
}
